/* eslint-disable no-console */
const rollup = require('rollup');
const path = require('path');
const chalk = require('chalk');
const generate = require('extract-ts-declaration').default;
const { getPlugins } = require('./rollup.plugin');
const utils = require('./utils');
const constant = require('./constant');

/**
 * @param {string} dir
 */
async function build(dir) {
  const options = rollup.defineConfig({
    input: path.resolve(dir, 'src', 'index.ts'),
    output: {
      banner: constant.BANNER,
      file: path.resolve(dir, 'dist', 'main.js'),
      format: 'esm',
      sourcemap: false,
    },
    plugins: getPlugins(dir, 'production'),
  });
  try {
    console.log(chalk.underline(`rollup ${rollup.VERSION} ${chalk.cyan('build start...')}`));
    const timestamp = Date.now();
    const bundle = await rollup.rollup(options);
    const { output } = await bundle.write(options.output);
    const filename = output.map((item) => item.fileName).join(',');

    console.log(
      chalk.green('created'),
      chalk.bold.green(filename),
      `in ${Date.now() - timestamp}ms`,
    );
    generate({
      input: options.input,
      output: path.resolve(dir, 'dist', 'typings'),
      autoClear: true,
    });
  } catch (error) {
    console.log(chalk.red('build failed', error.message, '\n', error.id));
  }
}

const root = utils.resolve('');
build(root);
